package jackson_demo1;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


public class AnimalDemo1 {
    public static void main(String[] args) throws Exception {
        // 创建 ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        // 创建 Dog 对象
        Animal dog = new Dog("Buddy", 3);

        // 序列化为 JSON
        String json = mapper.writeValueAsString(dog);
        byte[] bytes = mapper.writeValueAsBytes(dog);
        System.out.println(json);
        System.out.println(new String(bytes));

        Animal animal = mapper.readValue(json, Animal.class);
        System.out.println(animal instanceof Dog);
    }
}

// 父类 Animal
@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,              // 使用类型名称作为标识
        include = JsonTypeInfo.As.PROPERTY,      // 类型信息作为 JSON 的一个属性
        property = "type"                   // 类型信息的属性名
        ,visible = true
        , defaultImpl = Animal.class
)
@JsonSubTypes({
        @JsonSubTypes.Type(value = Dog.class, name = "dog"),  // 子类 Dog
        @JsonSubTypes.Type(value = Cat.class, name = "cat")   // 子类 Cat
})

@Data
@NoArgsConstructor
  class Animal {
    private String name;
    private String type;  // 用于存储类型信息的属性
    // 构造方法、getter 和 setter
    public Animal(String name) {
        this.name = name;
    }

}

// 子类 Dog
@AllArgsConstructor
@NoArgsConstructor
 class Dog extends Animal {
    private int age;

    // 构造方法、getter 和 setter
    public Dog(String name, int age) {
        super(name);
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

// 子类 Cat
 class Cat extends Animal {
    private boolean likesCream;

    // 构造方法、getter 和 setter
    public Cat(String name, boolean likesCream) {
        super(name);
        this.likesCream = likesCream;
    }

    public boolean isLikesCream() {
        return likesCream;
    }

    public void setLikesCream(boolean likesCream) {
        this.likesCream = likesCream;
    }

}
